package main

import (
	"fmt"
	_ "gitee.com/Diegoh/go-study/study/go-orm"
	"gitee.com/Diegoh/go-study/study/myjwt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	"log"
	"net/http"
	"time"
)

func main()  {
	fmt.Println("start study")
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {

		name := c.Query("name")
		c.JSON(200, gin.H{
			"message": name+"pong",
		})
	})
	r.POST("/p", func(c *gin.Context) {
		tokenStr := c.PostForm("token")
		header := c.GetHeader("token")
		fmt.Println("toekn:"+header)
		isValid := myjwt.ParseToekn(tokenStr)
		//jwt.Parse()
		nick := c.DefaultPostForm("nick", "anonymous") // 此方法可以设置默认值

		c.JSON(200, gin.H{
			"status":  "posted",
			"isValid": isValid,
			"nick":    nick,
		})
	})

	r.POST("/login",Login)
	r.Run(":3000") // listen and serve on 0.0.0.0:8080
}



type User struct {
	Name string `json:"name"`
	Password string `json:"password"`
	Age int `json:"age"`
}
func Login(c *gin.Context) {
	json := User{}
	err := c.BindJSON(&json)
	if err != nil {
		log.Printf("%v",err)
		return
	}
	log.Printf("%v",&json)

	jc := jwt.MapClaims{
			"username": json.Name,
			"password": json.Password,
			"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
		}
	tokenStr := myjwt.GenerateToken(&jc)
	c.JSON(http.StatusOK, gin.H{
		"name": json.Name,
		"password": json.Password,
		"age": json.Age,
		"token": tokenStr,
	})
}
